import socket
import threading
import time

# 服务端代码
def start_server():
    host = "0.0.0.0"  # 电脑本地IP
    port = 0            # 端口自定义

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)
    print(f"Python 服务器正在监听 {host}:{port}")

    while True:
        connection, address = server_socket.accept()
        print(f"来自 {address} 的连接")
        while True:
            message = connection.recv(1024).decode()
            if not message or message.lower() == 'exit':
                print(f"客户端断开连接: {address}")
                break
            print(f"收到来自 {address} 的消息: {message}")
            response = "服务器已收到消息"
            connection.send(response.encode())
        connection.close()

# 客户端代码
def start_client():
    host = "0.0.0.0"  # 替换为 QPython 服务器的 IP 地址
    port = 0            # 替换为 Qpython 服务器的端口
    retry_interval = 5  # 重试间隔时间（秒）

    while True:
        try:
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_socket.connect((host, port))
            print("已连接到 QPython 服务器可以开始发送消息")
            print("输入 'exit' 退出")
            print("如果发送消息就任意输入回车就好")
            break
        except ConnectionRefusedError:
            print(f"连接到 {host}:{port} 被拒绝{retry_interval} 秒后重试...")
            time.sleep(retry_interval)

    while True:
        message = input("发送消息: ")
        if message.lower() == 'exit':
            client_socket.send(message.encode())
            break
        client_socket.send(message.encode())

        response = client_socket.recv(1024).decode()
        print("服务器响应:", response)

    client_socket.close()
    print("连接已关闭")

if __name__ == "__main__":
    server_thread = threading.Thread(target=start_server)
    server_thread.daemon = True
    server_thread.start()

    time.sleep(1)

    start_client()